package pers.fjl.test.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pers.fjl.common.entity.QueryPageBean;
import pers.fjl.common.po.Department;
import pers.fjl.common.po.Staff;
import pers.fjl.test.dao.DeptDao;
import pers.fjl.test.dao.StaffDao;
import pers.fjl.test.service.StaffService;

import javax.annotation.Resource;

@Slf4j
@Service
public class StaffServiceImpl extends ServiceImpl<StaffDao, Staff> implements StaffService {
    @Resource
    private StaffDao staffDao;
    @Resource
    private StaffService staffService;
    @Resource
    private DeptDao deptDao;

    @Cacheable(value = {"StaffMap"})
    public Page<Staff> findPage(QueryPageBean queryPageBean) {
        //设置分页条件
        Page<Staff> page = new Page<>(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        //设置查询条件
        QueryWrapper<Staff> wrapper = new QueryWrapper<>();
        wrapper.like(queryPageBean.getQueryString() != null, "sname", queryPageBean.getQueryString());
        return staffDao.selectPage(page, wrapper);
    }

    /**
     * 修改两张表是一个事务
     * @param staff
     * @return flag
     */
    @Transactional
    @CacheEvict(value = {"StaffMap"}, allEntries = true)
    public boolean addStaff(Staff staff) {
        QueryWrapper<Staff> staffWrapper = new QueryWrapper<>();
        log.info("addStaff.staff.getsname():[{}]", staff.getSname());

        QueryWrapper<Department> deptWrapper = new QueryWrapper<>();
        deptWrapper.eq("did", staff.getDid());

        staffService.save(staff);
        //新增员工成功，此时要在部门表将部门人数加1

        Department dept = deptDao.selectOne(deptWrapper);
        QueryWrapper<Department> wrapper = new QueryWrapper<>();
        wrapper.eq("did", dept.getDid());
        dept.setPopulation(dept.getPopulation() + 1);
        deptDao.update(dept, deptWrapper);
        return true;
    }

    public boolean StaffExist(String sname) {//搜索用户名是否存在
        QueryWrapper<Staff> wrapper = new QueryWrapper<>();
        wrapper.select("1");
        wrapper.eq("sname", sname).last("limit 1");
        return staffDao.selectCount(wrapper) != 0;
    }
}
